package com.heima.article.service.impl;

import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IstaticLoading;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class StaticLoading implements IstaticLoading {

    @Autowired
    Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService apArticleService;

    @Override
    @Async
    public void staticLoading(ApArticle apArticle, String content) {
        try {
            Template template = configuration.getTemplate("article.ftl");

            Map<String,Object> map = new HashMap<>();
            map.put("content",content);
            StringWriter out = new StringWriter();
            template.process(map,out);
            InputStream is =  new ByteArrayInputStream(out.toString().getBytes());
            String url = minIOService.upload(apArticle.getId() + ".html", is, "text/html");
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
